package com.jjsc.auth.controller;

import com.jjsc.auth.form.LoginBody;
import com.jjsc.auth.form.RegisterBody;
import com.jjsc.auth.service.SysLoginService;
import com.jjsc.auth.service.WebLoginService;
import com.jjsc.common.core.domain.R;
import com.jjsc.common.core.utils.JwtUtils;
import com.jjsc.common.core.utils.StringUtils;
import com.jjsc.common.security.auth.AuthUtil;
import com.jjsc.common.security.service.TokenService;
import com.jjsc.common.security.utils.SecurityUtils;
import com.jjsc.system.api.model.LoginUser;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Author: 钟城明
 * @CreateTime: 2025-10-16
 * @Description:
 * @Version: 1.0
 */
@RestController
public class CustomerTokenController {
    @Autowired
    private TokenService tokenService;

    @Autowired
    private WebLoginService webLoginService;

    @Autowired
    private SysLoginService sysLoginService;

    @PostMapping("/h5/register")
    public R<?> register(@RequestBody RegisterBody registerBody) {
        // 用户注册
        webLoginService.register(registerBody);
        return R.ok();
    }

    @PostMapping("/h5/login")
    public R<?> login(@RequestBody LoginBody loginBody) {
        // 用户登录
        LoginUser loginUser = webLoginService.login(loginBody.getUsername(), loginBody.getPassword());
        // 获取登录token
        return R.ok(tokenService.createToken(loginUser));
    }

    @DeleteMapping("/h5/logout")
    public R<?> logout(HttpServletRequest request) {
        String token = SecurityUtils.getToken(request);
        if (StringUtils.isNotEmpty(token)) {
            String username = JwtUtils.getUserName(token);
            // 从redis中删除用户信息
            AuthUtil.logoutByToken(token);
            // 记录用户退出日志
            sysLoginService.logout(username);
        }
        return R.ok();
    }

}
